﻿<template>
	<div class="sys-file-container">
		<el-card shadow="hover" :body-style="{ paddingBottom: '0' }">
			<el-form :model="state.queryParams" ref="queryForm" :inline="true">
				<el-form-item :label="$t('message.gType.gCode')" prop="fileName">
					<el-input v-model="state.queryParams.GCode" :placeholder="$t('message.gType.gCode')" clearable />
				</el-form-item>
				<el-form-item :label="$t('message.gType.gModel')" prop="name">
						<el-input v-model="state.queryParams.GModel" :placeholder="$t('message.gType.gModel')" clearable />
				</el-form-item>
				<el-form-item :label="$t('message.gType.gName')" prop="code">
						<el-input v-model="state.queryParams.GName" :placeholder="$t('message.gType.gName')" clearable />
				</el-form-item>
				<el-form-item>
					<el-button-group>
             <el-button type="primary" icon="ele-Plus" @click="openaddgType" v-auth="'gType:add'"> {{ t('message.pageConfiguration.add') }} </el-button>
					
					
					</el-button-group>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" icon="ele-Search" @click="getData" v-auth="'sysFile:page'"> {{$t('message.pageConfiguration.query')}} </el-button>
				</el-form-item>
			</el-form>
		</el-card>

		<el-card class="full-table" shadow="hover" style="margin-top: 8px">
			<el-table :data="state.fileData" style="width: 100%" v-loading="state.loading" border>
				<el-table-column prop="gCode" :label="$t('message.gType.gCode')" width="55" align="center" />
				<el-table-column prop="gModel" :label="$t('message.gType.gModel')" minWidth="150" header-align="center" show-overflow-tooltip />
				<el-table-column prop="gName" :label="$t('message.gType.gName')" width="145" align="center" show-overflow-tooltip>
				</el-table-column>
				<el-table-column prop="cadFile" :label="$t('message.gType.cADFile')" align="center">
					<template #default="scope">
						<el-image
							style="width: 60px; height: 60px"
							:src="getFileUrlCAD(scope.row)"
							:alt="$t('message.gType.previewFailed')"
							:lazy="true"
							:hide-on-click-modal="true"
							:preview-src-list="[getFileUrlCAD(scope.row)]"
							:initial-index="0"
							fit="scale-down"
							preview-teleported
						>
							<template #error> </template>
						</el-image>
					</template>
				</el-table-column>
        	<el-table-column prop="gridFile" :label="$t('message.gType.gridFile')" align="center">
					<template #default="scope">
						<el-image
							style="width: 60px; height: 60px"
							:src="getFileUrlGrid(scope.row)"
							:alt="$t('message.gType.previewFailed')"
							:lazy="true"
							:hide-on-click-modal="true"
							:preview-src-list="[getFileUrlGrid(scope.row)]"
							:initial-index="0"
							fit="scale-down"
							preview-teleported
						>
							<template #error> </template>
						</el-image>
					</template>
				</el-table-column>
        	<el-table-column prop="vmFile" :label="$t('message.gType.vMFile')" align="center">
					<template #default="scope">
						<el-button @click="openVideoDialog(scope.row.vmFile)">Play</el-button>
					</template>
				</el-table-column>
				<el-table-column prop="length" :label="$t('message.gType.length')" align="center" show-overflow-tooltip />
				<el-table-column prop="width" :label="$t('message.gType.width')" align="center" show-overflow-tooltip />
				<el-table-column prop="efficiency" :label="$t('message.gType.efficiency')" align="center" show-overflow-tooltip />
				<el-table-column prop="robotModel" :label="$t('message.gType.robotModel')" align="center" show-overflow-tooltip />
        		<el-table-column prop="robotQty" :label="$t('message.gType.robotQty')" align="center" show-overflow-tooltip />
            		<el-table-column prop="blanketMode" :label="$t('message.gType.blanketMode')" align="center" show-overflow-tooltip />
                		<el-table-column prop="binType" :label="$t('message.gType.binType')" align="center" show-overflow-tooltip />
                    		<el-table-column prop="binSize" :label="$t('message.gType.binSize')" align="center" show-overflow-tooltip />
                        		<el-table-column prop="chargeQty" :label="$t('message.gType.chargeQty')" align="center" show-overflow-tooltip />
                            		<el-table-column prop="binQty" :label="$t('message.gType.binQty')" align="center" show-overflow-tooltip />
       		<el-table-column prop="packQty" :label="$t('message.gType.packQty')" align="center" show-overflow-tooltip />
                 		<el-table-column prop="createUserName" :label="$t('message.gType.createUserName')" align="center" show-overflow-tooltip />
                           		<el-table-column prop="updateUserName" :label="$t('message.gType.updateUserName')" align="center" show-overflow-tooltip />

				<el-table-column :label="$t('message.pageConfiguration.operate')" width="300" fixed="right" align="center" show-overflow-tooltip>
					<template #default="scope">
						<!-- <el-button icon="ele-View" size="small" text type="primary" @click="openFilePreviewDialog(scope.row)" v-auth="'sysFile:delete'"> {{$t('message.pageConfiguration.preview')}} </el-button> -->
						<!-- <el-button icon="ele-Download" size="small" text type="primary" @click="downloadFile(scope.row)" v-auth="'sysFile:downloadFile'"> {{$t('message.pageConfiguration.download')}} </el-button> -->
						      <el-button icon="ele-Edit" size="small" text="" type="primary" @click="openedit(scope.row)" v-auth="'gType:edit'"> {{ t('message.pageConfiguration.edit') }} </el-button>
             <el-button icon="ele-Delete" size="small" text="" type="danger" @click="delConfig(scope.row)" v-auth="'gType:delete'"> {{ t('message.pageConfiguration.del') }} </el-button>
					    
					</template>
				</el-table-column>
			</el-table>
			<el-pagination
				v-model:currentPage="state.tableParams.page"
				v-model:page-size="state.tableParams.pageSize"
				:total="state.tableParams.total"
				:page-sizes="[10, 20, 50, 100]"
				small
				background
				@size-change="handleSizeChange"
				@current-change="handleCurrentChange"
				layout="total, sizes, prev, pager, next, jumper"
			/>
		</el-card>

<el-dialog  v-model="videoDialogVisible" title="视频播放">
    <idv>
        <video width="640" height="360" controls>
          <source :src="videoUrl" type="video/mp4">
          您的浏览器不支持视频播放。
        </video>
   </idv>
      <template #footer>
        <el-button @click="videoDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>


		<el-dialog v-model="state.dialogUploadVisible" :lock-scroll="false" draggable width="400px">
			<template #header>
				<div style="color: #fff">
					<el-icon size="16" style="margin-right: 3px; display: inline; vertical-align: middle"> <ele-UploadFilled /> </el-icon>
					<span> {{ $t('message.pageConfiguration.uploadFile') }} </span>
				</div>
			</template>
			<div>
				<el-upload ref="uploadRef" drag :auto-upload="false" :limit="1" :file-list="state.fileList" action="" :on-change="handleChange" accept=".jpg,.png,.bmp,.gif,.txt,.pdf,.xlsx,.docx">
					<el-icon class="el-icon--upload">
						<ele-UploadFilled />
					</el-icon>
					<div class="el-upload__text">{{$t('message.pageConfiguration.operateTip')}}<em>{{$t('message.pageConfiguration.tips')}}</em></div>
					<template #tip>
						<div class="el-upload__tip">{{$t('message.pageConfiguration.importTip')}}</div>
					</template>
				</el-upload>
			</div>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="state.dialogUploadVisible = false">{{$t('message.pageConfiguration.cancel')}}</el-button>
					<el-button type="primary" @click="uploadFile">{{$t('message.pageConfiguration.confirm')}}</el-button>
				</span>
			</template>
		</el-dialog>

		<el-drawer :title="state.fileName" v-model="state.dialogDocxVisible" size="50%" destroy-on-close>
			<vue-office-docx :src="state.docxUrl" style="height: 100vh" @rendered="renderedHandler" @error="errorHandler" />
		</el-drawer>
		<el-drawer :title="state.fileName" v-model="state.dialogXlsxVisible" size="50%" destroy-on-close>
			<vue-office-excel :src="state.excelUrl" style="height: 100vh" @rendered="renderedHandler" @error="errorHandler"
		/></el-drawer>
		<el-drawer :title="state.fileName" v-model="state.dialogPdfVisible" size="50%" destroy-on-close>
			<vue-office-pdf :src="state.pdfUrl" style="height: 100vh" @rendered="renderedHandler" @error="errorHandler"
		/></el-drawer>
		<el-image-viewer v-if="state.showViewer" :url-list="state.previewList" @close="state.showViewer = false"></el-image-viewer>
		<EditSysFile ref="editSysFileRef" :title="$t('message.pageConfiguration.editFile')" @handleQuery="handleQuery" />

        <editDialog ref="editDialogRef" :title="state.editgTypeTitle" :groupList="state.groupList" @updateData="updateData" />
	</div>
</template>

<script lang="ts" setup name="sysFile">
import { onMounted, reactive, ref } from 'vue';
import { ElMessageBox, ElMessage, UploadInstance } from 'element-plus';
import VueOfficeDocx from '@vue-office/docx';
import VueOfficeExcel from '@vue-office/excel';
import VueOfficePdf from '@vue-office/pdf';
  import editDialog from '/@/views/main/gType/component/editDialog.vue'
import '@vue-office/docx/lib/index.css';
import '@vue-office/excel/lib/index.css';
  import { pageGType, deleteGType,batchDeleteGType,importGType ,downLoadGType  } from '/@/api/main/gType';
import EditSysFile from '/@/views/system/file/component/editSysFile.vue';

import { downloadByUrl } from '/@/utils/download';
import { getAPI } from '/@/utils/axios-utils';
import { SysFileApi } from '/@/api-services/api';
import { SysFile } from '/@/api-services/models';
import { useI18n } from 'vue-i18n';

const { t } = useI18n();

const videoDialogVisible = ref(false);
const videoUrl = ref('');
// const baseUrl = window.__env__.VITE_API_URL;
const uploadRef = ref<UploadInstance>();
const editSysFileRef = ref<InstanceType<typeof EditSysFile>>();
    const editDialogRef = ref();
const state = reactive({
	loading: false,
     groupList: [] as Array<String>,
      editgTypeTitle: '',
	fileData: [] ,
	queryParams: {
		SearchKey: undefined,
    GCode:undefined,
    GModel:undefined,
    GName:undefined
		
	},
	tableParams: {
		page: 1,
		pageSize: 10,
		total: 0 as any,
	},

	
	dialogUploadVisible: false,
	diaglogEditFile: false,
	fileList: [] as any,
	dialogDocxVisible: false,
	dialogXlsxVisible: false,
	dialogPdfVisible: false,
	showViewer: false,
	docxUrl: '',
	excelUrl: '',
	pdfUrl: '',
	fileName: '',
	previewList: [] as string[],
});

onMounted(async () => {
	getData();
});


const getData = async() => {
state.loading = true;

        var res = await  pageGType(Object.assign(state.queryParams));
console.log(res.data)
state.loading = false;
        state.fileData = res.data.result.items;
        
        };

const openVideoDialog = (url:string) => {
  console.log(url)
  videoUrl.value = url;
  videoDialogVisible.value = true;
};
// 查询操作
const handleQuery = async () => {
	if (state.queryParams.startTime == null) state.queryParams.startTime = undefined;
	if (state.queryParams.endTime == null) state.queryParams.endTime = undefined;

	state.loading = true;
	let params = Object.assign(state.queryParams, state.tableParams);
	var res = await getAPI(SysFileApi).apiSysFilePagePost(params);
	state.fileData = res.data.result?.items ?? [];
	state.tableParams.total = res.data.result?.total;
	state.loading = false;
};

// 重置操作
const resetQuery = () => {
	state.queryParams.fileName = undefined;
	state.queryParams.startTime = undefined;
	state.queryParams.endTime = undefined;
	handleQuery();
};

// 打开上传页面
const openUploadDialog = () => {
	state.fileList = [];
	state.dialogUploadVisible = true;
};

// 通过onChanne方法获得文件列表
const handleChange = (file: any, fileList: []) => {
	state.fileList = fileList;
};

 // 更新数据
          const updateData = () => {
      
          };



// 上传
const uploadFile = async () => {
	if (state.fileList.length < 1) return;
	await getAPI(SysFileApi).apiSysFileUploadFilePostForm(state.fileList[0].raw);
	handleQuery();
	ElMessage.success('上传成功');
	state.dialogUploadVisible = false;
};


        // 打开新增页面
          const openaddgType = () => {
          state.editgTypeTitle = t('message.gType.addgType');
          editDialogRef.value?.openDialog({});
          };

          // 打开编辑页面
          const openedit = (row: any) => {
          state.editgTypeTitle = t('message.gType.editgType');
          editDialogRef.value?.openDialog(row);
          };

          // 删除
          const delConfig = (row: any) => {
          ElMessageBox.confirm(t('message.messages.confirmDel')+`：【${row[tb.tableData.columns[1].prop.toString()]}】?`, t('message.messages.hint'), {
          confirmButtonText: t('message.messages.confirm'),
          cancelButtonText: t('message.messages.cancel'),
          type: 'warning',
          })
          .then(async () => {
          await deleteGType({ id: row.id });
          tableRef.value.handleList();
          ElMessage.success(t('message.messages.deleteSuccess'));
          })
          .catch(() => {});
          };


// 下载
const downloadFile = async (row: any) => {
	// var res = await getAPI(SysFileApi).sysFileDownloadPost({ id: row.id });
	var fileUrl = getFileUrl(row);
	downloadByUrl({ url: fileUrl });
};

// 删除
const delFile = (row: any) => {
	ElMessageBox.confirm(`确定删除文件：【${row.fileName}】?`, '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning',
	})
		.then(async () => {
			await getAPI(SysFileApi).apiSysFileDeletePost({ id: row.id });
			handleQuery();
			ElMessage.success('删除成功');
		})
		.catch(() => {});
};

// 打开文件预览页面
const openFilePreviewDialog = async (row: any) => {
	if (row.suffix == '.pdf') {
		state.fileName = `【${row.fileName}${row.suffix}】`;
		state.pdfUrl = getFileUrl(row);
		state.dialogPdfVisible = true;
	} else if (row.suffix == '.docx') {
		state.fileName = `【${row.fileName}${row.suffix}】`;
		state.docxUrl = getFileUrl(row);
		state.dialogDocxVisible = true;
	} else if (row.suffix == '.xlsx') {
		state.fileName = `【${row.fileName}${row.suffix}】`;
		state.excelUrl = getFileUrl(row);
		state.dialogXlsxVisible = true;
	} else if (['.jpg', '.png', '.jpeg', '.bmp'].findIndex((e) => e == row.suffix) > -1) {
		state.previewList = [getFileUrl(row)];
		state.showViewer = true;
	} else {
		ElMessage.error('此文件格式不支持预览');
	}
};

// 改变页面容量
const handleSizeChange = (val: number) => {
	state.tableParams.pageSize = val;
	handleQuery();
};

// 改变页码序号
const handleCurrentChange = (val: number) => {
	state.tableParams.page = val;
	handleQuery();
};

// 获取文件地址
const getFileUrl = (row: SysFile): string => {
  console.log(row)
	if (row.bucketName == 'Local') {
		return `/${row.filePath}/${row.id}${row.suffix}`;
	} else {
		return row.url!;
	}
};


const getFileUrlCAD = (row): string => {
  console.log(row)
	
		return row.cadFile;
	
};


const getFileUrlGrid = (row): string => {

		return row.gridFile;
	
};


const getFileUrlVM = (row): string => {
 
		return row.vmFile;
	
};

// 打开编辑页面
const openEditSysFile = (row: any) => {
	editSysFileRef.value?.openDialog(row);
};

// 文件渲染完成
const renderedHandler = () => {};
// 文件渲染失败
const errorHandler = () => {};


</script>
